var appid = '327289cf342a5549';
var key = '6LLcllayS1ivV387kP0K6OesDQPoj4ZX';
var from = 'zh-CHS';
var to = 'zh-CHT';

var jsonObj = {};
var taskArr = [];
var t = 0;

function fanyi(lang) {

  to = lang
  jsonObj = JSON.parse($('#old').val());
  start(jsonObj);
}


function start(obj) {
  for (let key in obj) {
    let val = obj[key];
    if (typeof val == 'object') {
      start(val);
    } else {
      let task = {
        text: val,
        o: obj,
        k: key,
      };
      taskArr.push(task);
    }
  }
  clearTimeout(t);
  t = setTimeout(() => {
    next();
  }, 1000);
}

async function next() {
  for (let i in taskArr) {
    task = taskArr[i];
    let val = await send(task.text);
    task.o[task.k] = val;
    shuaxin(task.o);
  }
  end();
}
//发送翻译请求
function send(item) {
  return new Promise((resolve, reject) => {
    //非字符串不允许翻译
    if (typeof item != 'string') {
      return resolve('无法翻译');
    }

    var appKey = '327289cf342a5549';
    var key = '6LLcllayS1ivV387kP0K6OesDQPoj4ZX';//注意：暴露appSecret，有被盗用造成损失的风险
    var salt = (new Date).getTime();
    var curtime = Math.round(new Date().getTime() / 1000);
    var query = item;
    // 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
    var from = 'zh-CHT';
    var str1 = appKey + truncate(query) + salt + curtime + key;
    var vocabId = '您的用户词表ID';
    var sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);
    $.ajax({
      url: 'https://openapi.youdao.com/api',
      type: 'post',
      dataType: 'jsonp',
      data: {
        q: query,
        appKey: appKey,
        salt: salt,
        from: from,
        to: to,
        sign: sign,
        signType: "v3",
        curtime: curtime,
        vocabId: vocabId,
      },
      success: function (data) {
        try{
          resolve(data.translation[0])
        }catch(e){
          resolve('无法翻译')

        }
      }
    });

  });
}
function truncate(q) {
  var len = q.length;
  if (len <= 20) return q;
  return q.substring(0, 10) + len + q.substring(len - 10, len);
}

function end() {
  var content = JSON.stringify(jsonObj);
  var blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
  saveAs(blob, 'en.json');
}

function shuaxin(obj) {
  $('#result').val('');
  var result = '{';
  for (var key in obj) {
    var str = '\n' + '"' + key + '"' + ':' + '"' + obj[key] + '"' + ',';
    result += str;
  }
  result = result + '\n' + '}';
  $('#result').val(result);
}
$('#zhToZh').click(function () { fanyi('zh-CHT') });
$('#zhToEn').click(function () { fanyi('en') });
$('#zhToEs').click(function () { fanyi('es') });
$('#zhToDe').click(function () { fanyi('de') });
$('#zhToFr').click(function () { fanyi('fr') });
$('#zhToKo').click(function () { fanyi('ko') });
$('#zhToJp').click(function () { fanyi('ja') });
$('#zhToPt').click(function () { fanyi('pt') });
$('#zhToIt').click(function () { fanyi('it') });
$('#zhToId').click(function () { fanyi('id') });

